package com.leshua.channel.mpos.shardjdbc;

import com.dangdang.ddframe.rdb.sharding.api.ShardingValue;
import com.dangdang.ddframe.rdb.sharding.api.strategy.table.SingleKeyTableShardingAlgorithm;
import com.google.common.collect.Range;

import java.util.Collection;
import java.util.LinkedHashSet;

public class SingleKeyDefaultTableShardingAlgorithm implements SingleKeyTableShardingAlgorithm<String> {

    @Override
    public String doEqualSharding(final Collection<String> availableTargetNames, final ShardingValue<String> shardingValue) {
        String tableNo = getTableNo(shardingValue.getValue());
        for (String each : availableTargetNames) {
            if (each.endsWith(tableNo)) {
                return each;
            }
        }
        throw new UnsupportedOperationException();
    }

    @Override
    public Collection<String> doInSharding(final Collection<String> availableTargetNames, final ShardingValue<String> shardingValue) {
        Collection<String> result = new LinkedHashSet<>(availableTargetNames.size());
        Collection<String> values = shardingValue.getValues();
        for (String value : values) {
            String tableNo = getTableNo(value);
            for (String each : availableTargetNames) {
                if (each.endsWith(tableNo)) {
                    result.add(each);
                }
            }
        }
        return result;
    }

    @Override
    public Collection<String> doBetweenSharding(final Collection<String> availableTargetNames, final ShardingValue<String> shardingValue) {
        Collection<String> result = new LinkedHashSet<>(availableTargetNames.size());
        Range<String> range = shardingValue.getValueRange();
        int lowwer = Integer.valueOf(getTableNo(range.lowerEndpoint()));
        int upper = Integer.valueOf(getTableNo(range.upperEndpoint()));
        for (int value = lowwer; value <= upper; value++) {
            String formatNo = String.format("%02d", value);
            for (String each : availableTargetNames) {
                if (each.endsWith(formatNo)) {
                    result.add(each);
                }
            }
        }
        return result;
    }

    private String getTableNo(String srcValue) {
        return srcValue.substring(8, 10);
    }
}
